<template>
  <div class="memeory-bg">
    <Header :isTransBg="true" :width="1000" :isGoBack="false">
      <template v-slot:left>
        <span class="weight-title">
          {{ checkedBookData.edition_name }}-{{ checkedBookData.grade_name }}
        </span>
      </template>
      <template v-slot:right>
        <!-- <div class="help-btn mr10" @click="helpDialog = true">
          <img
            class="ml5"
            slot="reference"
            src="@/assets/img/icon/help-normal.png"
            alt=""
          />
        </div> -->
        <div class="close-memeory" @click="goStudyCenter">
          关闭
          <img class="ml5" src="@/assets/img/close-circle.png" alt="" />
        </div>
      </template>
    </Header>
    <div class="memory-container w1000">
      <div class="memory-contain">
        <div class="memory-question">
          <div>
            <div class="memory-header">
              听音组句
              <span class="fr reminder-text">
                <!-- <span v-if="isIintensiveWord && intensiveWord.word_id" class="">
                  <span v-if="isIintensiveWord">四个选项快捷键为1/2/3/4,</span>
                  按"Enter"进入下一题
                </span> -->
                <span class="feedback-btn ml10 click" @click="showFeedBack">
                  反馈
                </span>
              </span>
            </div>
            <StudySentence
              v-if="sentenceData.sentence"
              :sentenceData="sentenceData"
              ref="studySentence"
              @answerTrue="answerTrue"
              @answerFalse="answerFalse"
              @nextSentence="nextSentence"
              studyType="sentenceExamples"
            ></StudySentence>
          </div>
        </div>
        <div v-if="!isReview">
          <span>
            <!-- 倒计时：{{ countTimerNum }} -->
          </span>

          <span>
            本次学习 [ 生句：{{ newWordNum }} 熟句：{{
              skilledNum
            }}
            本次复习：{{ reviewNum }} ]
          </span>
        </div>
        <div v-if="isReview">
          <span></span>
          <span>
            进度：{{ checkedSentenceIndex + 1 }} /
            {{ sentenceList.length }}
          </span>
        </div>
      </div>
    </div>
    <el-dialog
      title="帮助"
      :visible.sync="helpDialog"
      width="800px"
      class="memory-help"
    >
      <div>
        <div>
          <div class="mb30">
            <img src="../../../assets/img/step-study-2.png" alt="" />
          </div>
          <div class="mb10">
            <img src="../../../assets/img/step-study-1.png" alt="" />
          </div>
          <el-divider></el-divider>
          <div></div>
        </div>
        <div>
          <div class="key-point">
            <label>
              <span class="line"></span>
              <span>关键点:</span>
            </label>
            <div>
              <p class="point-info">点击认识或不认识一定要真实;</p>
              <p class="point-info">
                跟读时，
                <span class="red-color-text">单词+词义</span
                >一定要连起来，读出声;
              </p>
               <p class="point-info">
                认识的单词读<span class="red-color-text">一遍英文+一遍中文</span
                >；
              </p>
              <p class="point-info">
                不认识的单词读两轮，每一轮读<span class="red-color-text">四遍英文+一遍中文</span
                >；
              </p>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
    <Feedback
      ref="feedback"
      :type="1"
      :classify="2"
      @openDialog="isOpenMessageBox = true"
      @closeDialog="isOpenMessageBox = false"
    ></Feedback>
  </div>
</template>
<script>
import Header from "@/components/Header";
import StudySentence from "../components/StudySentence";
// import { Questions } from "@/api/index";
import Feedback from "@/components/Feedback";
// import { throttle } from "@/utils/utils";
import { addIntegral } from "@/api/index";
import {
  getStudySentenceList,
  sendSentenceStatus,
  getMemoryReview,
  getReviewNumber,
  setSentencePass,
} from "@/api/sentence";

export default {
  data() {
    return {
      sentenceList: [],
      sentenceData: {},
      checkedSentenceIndex: -1,
      groupData: {},
      initSkilledNum: 0,
      initReviewNum: 0,
      initNewWordNum: 0,
      countTimer: null,
      countTimerNum: 5,
      unitId: null,
      category: 0,
      checkedBookData: null,
      addIntegralNum: 0,
      helpDialog: false,
      isOpenMessageBox: false,
    };
  },
  computed: {
    skilledNum() {
      let data = this.sentenceList.filter((item) => {
        return !item.isReview && item.firstIsTrue === true;
      });
      return data.length + this.initSkilledNum;
    },
    reviewNum() {
      let data = this.sentenceList.filter((item) => {
        return (
          item.isReview &&
          (item.firstIsTrue === true || item.firstIsTrue === false)
        );
      });
      return data.length + this.initReviewNum;
    },
    newWordNum() {
      let data = this.sentenceList.filter((item) => {
        return !item.isReview && item.firstIsTrue === false;
      });
      return data.length + this.initNewWordNum;
    },
  },
  components: {
    StudySentence,
    Header,
    Feedback,
  },
  methods: {
    setInitWordNum() {
      let data1 = this.sentenceList.filter((item) => {
        return !item.isReview && item.checkAnswer === true;
      });
      let data2 = this.sentenceList.filter((item) => {
        return (
          item.isReview &&
          (item.checkAnswer === true || item.checkAnswer === false)
        );
      });
      let data3 = this.sentenceList.filter((item) => {
        return !item.isReview && item.checkAnswer === false;
      });
      this.initSkilledNum += data1.length;
      this.initReviewNum += data2.length;
      this.initNewWordNum += data3.length;
    },
    showFeedBack() {
      let id = this.sentenceData.sentence_id;
      if (id) {
        this.$refs.feedback.visible(id);
      }
    },
    nextSentence: function() {
      if (this.sentenceList.length <= 0) {
        return;
      }
      if (
        this.checkedSentenceIndex < this.sentenceList.length - 1 &&
        this.sentenceList.length > 0
      ) {
        this.checkedSentenceIndex++;
        this.setSentenceData(this.sentenceList[this.checkedSentenceIndex]);
      } else {
        this.getStudyData();
      }
    },
    setSentenceData(data) {
      this.sentenceData = data;
      this.sentenceData.startTime = new Date().getTime();
      // this.setCountTimer();
      this.$nextTick(() => {
        if (this.$refs.studySentence) {
          this.$refs.studySentence.initCom();
          // this.$refs.studySentence.playAudio("audioPlay");
        }
      });
    },

    setSentencePass(number) {
      number = number ? number : 0;
      return new Promise((reslove, reject) => {
        let data = {
          category: this.category,
          book_id: this.checkedBookData.book_id,
          sentence_id: this.sentenceData.sentence_id,
          memory_strength: 30 - number * 10 < 0 ? 0 : 30 - number * 10,
        };
        setSentencePass(data)
          .then((res) => {
            reslove(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    sendSentenceStatus(not) {
      let useTime = 0;
      if (this.sentenceData.endTime && this.sentenceData.startTime) {
        useTime = parseInt(
          (this.sentenceData.endTime - this.sentenceData.startTime) / 1000
        );
      }
      return new Promise((reslove, reject) => {
        let params = {
          not: not,
          bookId: this.checkedBookData.book_id,
          unitId: this.unitId,
          sentenceId: this.sentenceData.sentence_id,
          groupId: this.groupData.group_id,
          useTime: useTime,
          category: this.category,
          sid: this.sentenceData.sid,
        };

        sendSentenceStatus(params)
          .then((res) => {
            reslove(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    async answerTrue(data, fun) {
      //句子学习第一次是否正确
      this.sentenceData.endTime = new Date().getTime();
      if (this.isReview) {
        // 复习通过
        await this.setSentencePass(this.sentenceData.falseNum);
      } else {
        await this.sendSentenceStatus(data);
      }
      this.$set(this.sentenceData, "firstIsTrue", data);
      this.closeTimer();
      if (!this.isReview && !data) {
        if (this.checkedSentenceIndex + 3 < this.sentenceList.length) {
          console.log(this.checkedSentenceIndex + 3, this.sentenceList.length);
          this.sentenceList.splice(
            this.checkedSentenceIndex + 3,
            0,
            Object.assign({}, this.sentenceData, {
              isReview: true,
              firstIsTrue: null,
            })
          );
        } else {
          this.sentenceList.push(
            Object.assign({}, this.sentenceData, {
              isReview: true,
              firstIsTrue: null,
            })
          );
        }
      }
      if (fun) {
        fun();
      }
    },
    answerFalse() {
      if (!this.sentenceData.falseNum) {
        this.sentenceData.falseNum = 0;
      }
      this.sentenceData.falseNum++;
    },
    goStudyCenter() {
      this.$router.push({
        name: "sentenceStudyCenter",
      });
    },
    getStudySentenceList() {
      let params = {
        unitId: this.unitId,
        bookId: this.checkedBookData.book_id,
        number: this.checkedBookData.number,
        source: this.category,
      };
      getStudySentenceList(params).then((res) => {
        if (
          res.code == 200 &&
          res.data &&
          res.data.list &&
          res.data.list.length > 0
        ) {
          if (
            this.groupData &&
            this.groupData.group_id &&
            this.groupData.group_id !== res.data.group_id
          ) {
            this.addIntegral(this.groupData.group_id);
            this.setInitWordNum();
          }
          // 结算学币
          res.data.list.forEach((item) => {
            // 句子
            item.sentence = item.content;
            // 释义
            item.paraphrase = item.translation;
            // 音频
            item.audioURL = item.audio_src;
            // id
          });
          this.checkedSentenceIndex = -1;
          this.groupData = res.data;
          let sentenceListData = res.data.list.filter((sentence) => {
            sentence.checkedNum = 0;
            sentence.wrongNum = 0;
            return sentence.correct_num < 1;
          });
          if (sentenceListData.length > 0) {
            this.sentenceList = sentenceListData;
            this.nextSentence();
          }
        } else {
          if (this.groupData && this.groupData.group_id) {
            this.addIntegral(this.groupData.group_id);
          }
          if (!this.isOpenMessageBox) {
            this.isOpenMessageBox = true;
            this.$confirm("听音组句学习已完成,前往极速挑战", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              showClose: true,
              distinguishCancelAndClose: true,
              closeOnClickModal: false,
              closeOnPressEscape: false,
              beforeClose: (action, instance, done) => {
                this.$beforeConfirmClose(action, instance, done);
              },
            })
              .then(() => {
                this.isOpenMessageBox = false;
                this.$router.push({
                  name: "sentenceTest",
                  query: {
                    unitId: this.unitId,
                    category: this.category,
                    mode: 1,
                  },
                });
              })
              .catch(() => {
                this.isOpenMessageBox = false;
                this.goStudyCenter();
              });
          }
        }
      });
    },
    setCountTimer() {
      this.countTimerNum = 5;
      if (this.countTimer) {
        clearInterval(this.countTimer);
      }
      this.countTimer = setInterval(() => {
        this.countTimerNum--;
      }, 1000);
    },
    getMemoryReview() {
      let params = {
        pageNum: 1,
        pageSize: 10,
        category: this.category,
        bookId: this.checkedBookData.book_id,
      };
      getMemoryReview(params).then(async (res) => {
        if (res.code == 200 && res.data) {
          res.data.list.forEach((item) => {
            // 句子
            item.sentence = item.content;
            // 释义
            item.paraphrase = item.translation;
            // 音频
            item.audioURL = item.audio_src;
          });
          let data = res.data.list.filter((item) => {
            item.checkedNum = 0;
            item.wrongNum = 0;
            return item.is_review <= 0;
          });

          if (data.length > 0) {
            this.checkedSentenceIndex = -1;
            this.sentenceList = data;
            this.nextSentence();
          } else {
            this.nextReview();
          }
        } else {
          this.nextReview();
        }
      });
    },
    async nextReview() {
      if (!this.isOpenMessageBox) {
        let nextData = await this.getReviewNumber();
        if (nextData) {
          this.isOpenMessageBox = true;
          this.$confirm(
            `${
              this.$store.getters.sentenceCategory[this.category].title
            }已复习完成，是否前往${
              this.$store.getters.sentenceCategory[nextData.category].title
            }复习`,
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              closeOnClickModal: false,
              closeOnPressEscape: false,
            }
          )
            .then(() => {
              this.isOpenMessageBox = false;
              this.$router.push({
                name: this.$store.getters.sentenceCategory[nextData.category]
                  .route,
                query: {
                  isReview: true,
                },
              });
            })
            .catch(() => {
              this.isOpenMessageBox = false;
              this.goStudyCenter();
              return false;
            });
        } else {
          this.$alert(
            `${
              this.$store.getters.sentenceCategory[this.category].title
            }已复习完成`,
            "提示",
            {
              confirmButtonText: "确定",
              callback: () => {
                this.isOpenMessageBox = false;
                this.goStudyCenter();
              },
            }
          );
          // this.$confirm(
          //   `${
          //     this.$store.getters.sentenceCategory[this.category].title
          //   }已复习完成`,
          //   "提示",
          //   {
          //     confirmButtonText: "返回学习中心",
          //     cancelButtonText: "取消",
          //     closeOnClickModal: false,
          //     closeOnPressEscape: false,
          //   }
          // )
          //   .then(() => {
          //     this.isOpenMessageBox = false;
          //     this.goStudyCenter();
          //   })
          //   .catch(() => {
          //     this.isOpenMessageBox = false;
          //     return false;
          //   });
        }
      }
    },
    getReviewNumber() {
      return new Promise((reslove) => {
        getReviewNumber(this.checkedBookData.book_id)
          .then((res) => {
            if (res.code == 200 && res.data) {
              console.log(res);
              let data = res.data.filter((item) => {
                return item.category > this.category && item.num > 0;
              });
              if (data.length > 0) {
                reslove(data[0]);
              }
            }
            reslove(null);
          })
          .catch(() => {
            reslove(null);
          });
      });
    },
    getStudyData() {
      if (this.isReview) {
        this.getMemoryReview();
      } else {
        this.getStudySentenceList();
      }
    },
    closeTimer() {
      clearInterval(this.countTimer);
    },
    addIntegral(groupId) {
      let params = {
        groupId,
        source: this.category,
        bookId: this.checkedBookData.book_id,
        unitId: this.unitId,
        type: 2,
      };
      addIntegral(params).then((res) => {
        if (res.code == 200) {
          this.addIntegralNum += res.data;
        }
      });
    },
  },
  created() {
    this.checkedBookData = JSON.parse(localStorage.getItem("bookData"));
    let data = this.checkedBookData.word_book_vo_list.filter((item) => {
      return item.source == this.category;
    });
    if (data.length > 0) {
      this.checkedBookData.number = data[0].number;
    } else {
      this.checkedBookData.number = 1;
    }
    this.unitId = this.$route.query.unitId;
    this.isReview = !!this.$route.query.isReview;
    this.getStudyData();
  },
  mounted() {},
  beforeDestroy() {
    this.closeTimer();
  },
};
</script>
